package cn.nkpro.elcube.co.quartz;

import cn.nkpro.elcube.annotation.NkNote;
import cn.nkpro.elcube.basic.NkProperties;
import cn.nkpro.elcube.exception.NkSystemException;
import cn.nkpro.elcube.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;

@NkNote("定时清理tmp文件")
@Slf4j
@NkScheduled(cron = "0 0 0 * * ?")
public class NkEmptyTmpQuartzJob extends NkAbstractQuartzJob {

    private Format format = new SimpleDateFormat(String.format("yyyyMMdd%sHHmmss", File.separator));

    @Autowired
    private NkProperties properties;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        String tmp = String.join(File.separator, properties.getFileRootPath(), "tmp");
        File directoryFile = new File(tmp);
        // 判断directory对应的文件是否存在，或者是否是一个文件夹
        if (!directoryFile.exists() || !directoryFile.isDirectory()) {
            throw new NkSystemException("文件夹删除失败，文件夹不存在" + tmp);
        }
        File[] files = directoryFile.listFiles();
        if (null != files) {
            //创建Calendar实例
            Calendar cal = Calendar.getInstance();
            //获取前两天
            cal.add(Calendar.DATE, -2);
            String twoDayBefore = format.format(cal.getTime());
            for (File file : files) {  // 循环删除所有的子文件及子文件夹
                // 删除子文件
                if (file.isDirectory()) {
                    String name = file.getName();
                    if (name.compareTo(twoDayBefore) < 0) {
                        FileUtils.deleteDirectory(tmp + "/" + name);
                    }
                }
            }
        } else {
            throw new NkSystemException("没有需要删除的文件");
        }
    }
}
